package com.milhouz.pokertimer;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;

import com.milhouz.pokertimer.constant.LogConstant;
import com.milhouz.pokertimer.constant.PriceRateConstant;
import com.milhouz.pokertimer.model.AbstractPkr;

/**
 * Example that shows finding a preference from the hierarchy and a custom preference type.
 */
public class PokerTimerPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

	public static final String GAME_PREFERENCES = "GAME_PREFERENCES";
	
	public Preference prefNbPlayers;
	public Preference prefStartingStack;
	public Preference prefPlayerFee;
	public Preference prefNbPrice;
	public Preference prefFirstSmallBlind;
	public Preference prefBlindStep;
	public Preference prefTimeround;
	public Preference prefPriceListPercent;
	public ListPreference prefPricePattern;
	public PreferenceScreen prefPriceList;
	public PreferenceScreen prefBlindList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(LogConstant.LOG_TAG, "onCreate pref");

		// initialize preferences screen
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		
		getPreferenceManager().setSharedPreferencesName(GAME_PREFERENCES);
		getPreferenceManager().setSharedPreferencesMode(MODE_PRIVATE);
		
		// retrieve components
		prefNbPlayers = (Preference) getPreferenceScreen().findPreference("nbPlayers");
		prefStartingStack = (Preference) getPreferenceScreen().findPreference("startingStack");
		prefPlayerFee = (Preference) getPreferenceScreen().findPreference("playerFee");
		prefNbPrice = (Preference) getPreferenceScreen().findPreference("nbPrizes");
		prefFirstSmallBlind = (Preference) getPreferenceScreen().findPreference("firstSmallBlind");
		prefBlindStep = (Preference) getPreferenceScreen().findPreference("blindStep");
		prefTimeround = (Preference) getPreferenceScreen().findPreference("timeRound");
		prefPricePattern = (ListPreference) getPreferenceScreen().findPreference("pricePatternList");
		prefPriceList = (PreferenceScreen) getPreferenceScreen().findPreference("prizeStructure");
		prefBlindList = (PreferenceScreen) getPreferenceScreen().findPreference("blindStructure");
		prefPriceListPercent = (Preference) getPreferenceScreen().findPreference("pricePatternList");
		
		// update title of the total player preference
		prefNbPlayers.setTitle(getString(R.string.pref_maindata_players) + " : " + 
											getPreferenceScreen().getSharedPreferences().getString("nbPlayers", getString(R.string.default_players)));
		prefPlayerFee.setTitle(getString(R.string.pref_prizes_playerfee) + " " +
											getPreferenceScreen().getSharedPreferences().getString("playerFee", getString(R.string.default_playerfee)) + " $");
		prefNbPrice.setTitle(getString(R.string.pref_prizes_nbprizes) + " : " +
											getPreferenceScreen().getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices)));
		prefFirstSmallBlind.setTitle(getString(R.string.pref_blinds_firstsmallblind) + " " + 
											getPreferenceScreen().getSharedPreferences().getString("firstSmallBlind", getString(R.string.default_firstsmallblind)));
		prefBlindStep.setTitle(getString(R.string.pref_blinds_blindstep) + " " + 
											getPreferenceScreen().getSharedPreferences().getString("blindStep", getString(R.string.default_blindstep)));
		prefTimeround.setTitle(getString(R.string.pref_blinds_timeround) + " " + 
											getPreferenceScreen().getSharedPreferences().getString("timeRound", getString(R.string.default_timeround)) + " min");
		prefPriceListPercent.setSummary(PriceRateConstant.getPercentsByNbWinnerAndSelectedPattern(
				Integer.valueOf(prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices))),
				Integer.valueOf(prefPriceListPercent.getSharedPreferences().getString("pricePatternList","1"))));
		
		// update summary of starting stack preference
		String nb = getPreferenceScreen().getSharedPreferences().getString("nbPlayers", getString(R.string.default_players));
		String stack = getPreferenceScreen().getSharedPreferences().getString("startingStack", getString(R.string.default_stack));
		prefStartingStack.setTitle(getString(R.string.pref_maindata_startstack_desc1) + " " + stack);
		prefStartingStack.setSummary(getString(R.string.pref_maindata_startstack_desc2) + " " + (Integer.valueOf(nb) * Integer.valueOf(stack)));
		
		updatePrices();
		updateBlinds();
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		Log.i(LogConstant.LOG_TAG, "* Shared Preference Changed : " + key);
		if (key.equals("nbPlayers") || key.equals("startingStack")) {
			// update title of the total player preference
			prefNbPlayers.setTitle(getString(R.string.pref_maindata_players) + " : " + 
														 prefNbPlayers.getSharedPreferences().getString("nbPlayers", getString(R.string.default_players)));
			// update summary
			String nb = sharedPreferences.getString("nbPlayers", getString(R.string.default_players));
			String stack = sharedPreferences.getString("startingStack", getString(R.string.default_stack));
			prefStartingStack.setTitle(getString(R.string.pref_maindata_startstack_desc1) + " " + stack);
			prefStartingStack.setSummary(getString(R.string.pref_maindata_startstack_desc2) + " " + (Integer.valueOf(nb) * Integer.valueOf(stack)));
			updatePrices();
		}	else if (key.equals("playerFee")) {	
			prefPlayerFee.setTitle(getString(R.string.pref_prizes_playerfee) + " " + 
					prefPlayerFee.getSharedPreferences().getString("playerFee", getString(R.string.default_playerfee)) + " $");
			prefPriceListPercent.setSummary(PriceRateConstant.getPercentsByNbWinnerAndSelectedPattern(
					Integer.valueOf(prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices))),
					Integer.valueOf(prefPriceListPercent.getSharedPreferences().getString("pricePatternList","1"))));
			updatePrices();
		}	else if (key.equals("nbPrizes")) {	
			prefNbPrice.setTitle(getString(R.string.pref_prizes_nbprizes) +  " : " + 
					prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices)));
			prefPriceListPercent.setSummary(PriceRateConstant.getPercentsByNbWinnerAndSelectedPattern(
					Integer.valueOf(prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices))),
					Integer.valueOf(prefPriceListPercent.getSharedPreferences().getString("pricePatternList","1"))));
			updatePrices();
		}	else if (key.equals("firstSmallBlind")) {	
			prefFirstSmallBlind.setTitle(getString(R.string.pref_blinds_firstsmallblind) + " " +  
					prefFirstSmallBlind.getSharedPreferences().getString("firstSmallBlind", getString(R.string.default_firstsmallblind)));
			updateBlinds();
		}	else if (key.equals("blindStep")) {
			prefBlindStep.setTitle(getString(R.string.pref_blinds_blindstep) + " " +  
					prefBlindStep.getSharedPreferences().getString("blindStep", getString(R.string.default_blindstep)));
			updateBlinds();
		}	else if (key.equals("timeRound")) {
			prefTimeround.setTitle(getString(R.string.pref_blinds_timeround) + " " +  
					prefTimeround.getSharedPreferences().getString("timeRound", getString(R.string.default_timeround)) + " min");
			updateBlinds();
		}	else if (key.equals("pricePatternList")) {
			prefPriceListPercent.setSummary(PriceRateConstant.getPercentsByNbWinnerAndSelectedPattern(
							Integer.valueOf(prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices))),
							Integer.valueOf(prefPriceListPercent.getSharedPreferences().getString("pricePatternList","1"))));
			updatePrices();
		}
	}
	
	private void updatePrices() {
		Log.i(LogConstant.LOG_TAG, "> Update Prices List");
		// clean price list
		if (prefPriceList.getPreferenceCount() != 0) {
			Log.d(LogConstant.LOG_TAG, "  Clear price list.");
			prefPriceList.removeAll();
		} else {
			Log.d(LogConstant.LOG_TAG, "  No price list.");			
		}
		
		Preference pricePref = null;
		Integer nbPlayers = Integer.valueOf(prefNbPlayers.getSharedPreferences().getString("nbPlayers", getString(R.string.default_players)));
		Integer nbPrice = Integer.valueOf(prefNbPrice.getSharedPreferences().getString("nbPrizes", getString(R.string.default_nbprices)));
		Integer playerFee = Integer.valueOf(prefPlayerFee.getSharedPreferences().getString("playerFee", getString(R.string.default_playerfee)));

		prefPricePattern.setEntries(PriceRateConstant.getPatternsByNbWinners(nbPrice));
		prefPricePattern.setEntryValues(PriceRateConstant.getPatternsIndexByNbWinners(nbPrice));
		
		if (PriceRateConstant.PRICE_RATE.get(nbPrice) != null) {
			Integer selectedPattern = Integer.valueOf(prefPlayerFee.getSharedPreferences().getString("pricePatternList", "1"));
			for (int i=1; i<=nbPrice; i++) {
				pricePref = new Preference(getApplicationContext());
				pricePref.setKey("pricesPercentages_" + i);
				pricePref.setTitle("Place " + i + " : "
						+ (((playerFee * nbPlayers) * PriceRateConstant.PRICE_RATE.get(nbPrice).get(selectedPattern).get(i)) / 100) + " $"
						+ " - " + PriceRateConstant.PRICE_RATE.get(nbPrice).get(selectedPattern).get(i) + "%");
				prefPriceList.addPreference(pricePref);
			}
		}
	}
	
	
	
	private void updateBlinds() {
		Log.i(LogConstant.LOG_TAG, "> Update Blinds List");
		// clean blind list
		if (prefBlindList.getPreferenceCount() != 0) {
			Log.d(LogConstant.LOG_TAG, "  Clear blind list.");
			prefBlindList.removeAll();
		} else {
			Log.d(LogConstant.LOG_TAG, "  No blind list.");			
		}
		Preference blindPref = null;
		Integer smallblind = Integer.valueOf(prefFirstSmallBlind.getSharedPreferences().getString("firstSmallBlind", getString(R.string.default_firstsmallblind)));
		Integer bigblind = smallblind * 2;
		Integer step = Integer.valueOf(prefBlindStep.getSharedPreferences().getString("blindStep", getString(R.string.default_blindstep)));
		Integer time = Integer.valueOf(prefTimeround.getSharedPreferences().getString("timeRound", getString(R.string.default_timeround)));
		for (int i=1; i <= AbstractPkr.NB_ROUNDS; i++ ) {
			blindPref = new Preference(getApplicationContext());
			blindPref.setKey("blinds_" + i);
			blindPref.setTitle("Round " + i);
			blindPref.setSummary("Small Blind : " + smallblind + " - Big Blind : " + bigblind + " - Temps : " + time);
			prefBlindList.addPreference(blindPref);
			smallblind = smallblind + step;
			bigblind = smallblind * 2;
		}
	}
	
   @Override
   protected void onResume() {
       super.onResume();
       getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
   }

   @Override
   protected void onPause() {
       super.onPause();
       getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
   }

}
